package cn.topartip.filters;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Configuration
public class AuthCheckerFilter03 implements GlobalFilter, Ordered {
    @NacosValue(value = "${auth.typeKey}",autoRefreshed = true)
    String authTypeKey;
    @NacosValue(value = "${auth.uidKey}",autoRefreshed = true)
    String uid;
    @NacosValue(value = "${auth.groupIdKey}",autoRefreshed = true)
    String groupIdKey;
    @NacosValue(value = "${auth.utkKey}",autoRefreshed = true)
    String utkKey;



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String authType = exchange.getRequest().getHeaders().getFirst(authTypeKey);
        //如果在白名单内
        if(Objects.equals(authType, "whiteList"))return chain.filter(exchange);

        //如果需要登录和权限校验
        if (Objects.equals(authType, "needAuth")){
            String  utk = exchange.getRequest().getHeaders().getFirst(utkKey);
            /*如果没有UTK中断*/
            if (utk == null || utk.isEmpty()) return Mono.empty();

            /*去REDIS检测如果UTK是否过期，如果过期返回需要重新登录，否则获取UTK的 urg参数组写入头部 */
            String redisKey=utkKey +"_"+ utk;



            //带有URG参数组的头部走下去

            return chain.filter(exchange);
        }
        return Mono.empty();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+102;
    }
}
